#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年3月8日

@author: Administrator
'''
from account import settings
from account.models import Profile
from common.decorators import login_required
from common.utils import tool, es
from django.contrib.auth.models import User
from django.http.response import HttpResponse
from django.template.response import TemplateResponse
from elasticsearch_dsl.query import Q
from elasticsearch_dsl.search import Search
from funcresource.decorators import user_funcresource
from funcresource.models import UserResource, Resource, FuncResource, \
    UserFunctional, Functional
import copy
import ujson as json


@login_required
@user_funcresource
def index(request, template="account/admin/user/userlist.html"):
    """
        func:
                               用户列表页面
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    return TemplateResponse(request, template, rsp_data)
    
@login_required
def list(request):
    """
        func:
                               用户列表
        parameters:
            start:开始下标
            length:每页展示个数
            search[value]:搜索关键字
            columns[6][search][value]:用户状态
            draw:渲染次数
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = []
    start = int(request.POST['start'])
    length = int(request.POST['length'])
    keyword = request.POST["search[value]"]
    is_active = request.POST.get("columns[6][search][value]", "")
    is_active = '' if is_active == '' else is_active[1:-1]
    draw = request.POST['draw']
    #es连接
    response = Search(using=es.es_client, index=settings.ES_INDEX_USER_LIST, doc_type=settings.ES_INDEX_USER_LIST_TYPE) 
    if  keyword:
        response = response.query(Q("match_phrase", username=keyword) | Q("match_phrase", first_name=keyword) | Q("match_phrase", mobile=keyword) | Q("match_phrase", email=keyword)) 
    if  is_active:
        response = response.query(Q("term", is_active=is_active)) 
        
    response = response.extra(from_=start, size=length) 
    response = response.sort("id")
    result = response.execute()
    for hit in result.hits:
        record = {
            "id":hit.id,
            "username":hit.username,
            "first_name":hit.first_name,
            "email":hit.email,
            "is_active_desc":u'正常' if hit.is_active == 1 else '已删除',
            "is_active":hit.is_active,
            "date_joined":hit.date_joined,
            "user_type":hit.utype_desc,
            "mobile":hit.mobile,
        }
        rsp_data["data"].append(record)
    rsp_data["recordsTotal"] = result.hits.total
    rsp_data["recordsFiltered"] = result.hits.total
    rsp_data["draw"] = draw
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def all(request):
    """
        func:
                               所有用户
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["users"] = []
    users = User.objects.filter(is_active=True)
    for user in users:
        record = {
            "id":user.id,
            "name":user.first_name if user.first_name else user.username,
        }
        rsp_data["data"]["users"].append(record)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def edit(request, template="account/admin/user/edituser.html"):
    """
        func:
                               编辑用户信息页面
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    user_id = request.GET["user_id"]
    rsp_data["data"]["user"] = {} 
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    rsp_data["data"]["user"] = {
        "id":user.id,
        "username":user.username,
        "first_name":user.first_name,
        "is_active":user.is_active,
        "email":user.email,
        "user_type":"",
        "mobile":"",
        "sex":"",
        "avatar_url":"",
    }
    try:
        rsp_data["data"]["user"]["user_type"] = user.profile.utype if user.profile else ""
        rsp_data["data"]["user"]["mobile"] = user.profile.mobile if user.profile else ""
        rsp_data["data"]["user"]["sex"] = user.profile.sex if user.profile else ""
        rsp_data["data"]["user"]["avatar_url"] = user.profile.avatar_url if user.profile else ""
    except Profile.DoesNotExist:
        pass
    rsp_data["data"]["sexs"] = [{"id":sex[0], "name":sex[1]} for sex in settings.USER_SEX_CHOICES]
    rsp_data["data"]["user_types"] = [{"id":utype[0], "name":utype[1]} for utype in settings.USER_TYPE_CHOICES]
    return TemplateResponse(request, template, rsp_data)

@login_required
def detail(request, template="account/admin/user/userdetail.html"):
    """
        func:
                               用户详情
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["user"] = {} 
    user_id = request.GET["user_id"]
    
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    rsp_data["data"]["user"] = {
        "id":user.id,
        "username":user.username,
        "first_name":user.first_name,
        "is_active":u"正常" if user.is_active else u"已停用",
        "email":user.email,
        "user_type":"",
        "mobile":"",
        "sex":"",
        "avatar_url":"",
    }
    try:
        rsp_data["data"]["user"]["user_type"] = settings.USER_TYPE_CHOICES[user.profile.utype][1] if user.profile else ""
        rsp_data["data"]["user"]["mobile"] = user.profile.mobile if user.profile else ""
        rsp_data["data"]["user"]["sex"] = user.profile.sex if user.profile else ""
        rsp_data["data"]["user"]["avatar_url"] = user.profile.avatar_url if user.profile else ""
    except Profile.DoesNotExist:
        pass
    rsp_data["data"]["sexs"] = [{"id":sex[0], "name":sex[1]} for sex in settings.USER_SEX_CHOICES]
    return TemplateResponse(request, template, rsp_data)

@login_required
def user_resource(request, template="account/admin/user/userresource.html"):
    """
        func:
                               用户资源页面
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    user_id = request.GET["user_id"]
    rsp_data["data"]["user_id"] = request.GET["user_id"]
    try:
        User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    return TemplateResponse(request, template, rsp_data)

@login_required
def user_resource_list(request):
    """
        func:
                               用户资源
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["resources"] = [] 
    user_id = request.POST["user_id"]
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    resources = Resource.objects.filter(state=settings.StateEnum.VALID, parent=None)
    for resource in resources:
        record = {
            "id":str(resource.id),
            "text":resource.name,
            "state":{"opened":True},
            "children":[]
        }
        childrens = Resource.objects.filter(state=settings.StateEnum.VALID, parent=resource)
        for children in childrens:
            r_children = {
                "id":str(children.id),
                "text":children.name,
                "state":{"opened":True},
                "icon":"none"
            }
            if UserResource.objects.filter(user=user, resource=children, state=settings.StateEnum.VALID).exists():
                r_children["state"]["selected"] = True
            record["children"].append(r_children)
        if UserResource.objects.filter(user=user, resource=children, state=settings.StateEnum.VALID).exists():
            r_children["state"]["selected"] = True
        rsp_data["data"]["resources"].append(record)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def save_resource(request):
    """
        func:
                                新增用户
        parameters:
            username:用户名
            first_name:昵称
            password:密码
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    user_id = request.POST["user_id"]
    node_ids = request.POST["node_ids"]
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    node_ids = node_ids.split(",")
    uresources = UserResource.objects.filter(user=user)
    uresources.filter(state=settings.StateEnum.VALID).exclude(resource_id__in=node_ids).update(state=settings.StateEnum.DELETED)
    uresources.filter(resource_id__in=node_ids, state=settings.StateEnum.DELETED).update(state=settings.StateEnum.VALID)
    uresource_ids = uresources.values_list("resource_id", flat=True)
    for node_id in node_ids:
        if not int(node_id) in uresource_ids:
            UserResource.objects.create(user=user, resource_id=node_id)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def user_funcresource(request, template="account/admin/user/userfuncresource.html"):
    """
        func:
                               用户资源页面
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    user_id = request.GET["user_id"]
    rsp_data["data"]["user_id"] = request.GET["user_id"]
    try:
        User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    return TemplateResponse(request, template, rsp_data)
    

@login_required
def user_funcresource_list(request):
    """
        func:
                               用户资源
        parameters:
            user_id:用户id
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    rsp_data["data"] = {}
    rsp_data["data"]["funcresources"] = [] 
    user_id = request.POST["user_id"]
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    funcresources = FuncResource.objects.filter(state=settings.StateEnum.VALID)
    for funcresource in funcresources:
        record = {
            "id":'%s_%s' % ("parent", funcresource.id),
            "text":funcresource.name,
            "state":{"opened":True},
            "children":[]
        }
        childrens = Functional.objects.filter(state=settings.StateEnum.VALID, func_resource=funcresource)
        for children in childrens:
            r_children = {
                "id":str(children.id),
                "text":children.name,
                "state":{"opened":True},
                "icon":"none",
            }
            if UserFunctional.objects.filter(user=user, func=children, state=settings.StateEnum.VALID).exists():
                r_children["state"]["selected"] = True
            record["children"].append(r_children)
        rsp_data["data"]["funcresources"].append(record)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def save_funcresource(request):
    """
        func:
                                新增用户
        parameters:
            username:用户名
            first_name:昵称
            password:密码
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    user_id = request.POST["user_id"]
    node_ids = request.POST["node_ids"]
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    node_ids = node_ids.split(",")
    ufuncs = UserFunctional.objects.filter(user=user)
    ufuncs.filter(state=settings.StateEnum.VALID).exclude(func_id__in=node_ids).update(state=settings.StateEnum.DELETED)
    ufuncs.filter(func_id__in=node_ids, state=settings.StateEnum.DELETED).update(state=settings.StateEnum.VALID)
    func_ids = ufuncs.values_list("func_id", flat=True)
    for node_id in node_ids:
        if not int(node_id) in func_ids:
            UserFunctional.objects.create(user=user, func_id=node_id)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def save(request):
    """
        func:
                                新增用户
        parameters:
            username:用户名
            first_name:昵称
            password:密码
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    username = request.POST["username"]
    firstname = request.POST["firstname"]
    password = request.POST["password"]
    if tool.is_email(username):
        if User.objects.filter(Q(username=username) | Q(email=username)).exists():
            rsp_data = copy.copy(settings.ERROR["EXIST_ERR"])
            rsp_data["msg"] = u"用户已存在"
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
        
        user = User.objects.create_user(username, username, password)
    elif tool.is_mobile(username):
        if User.objects.filter(username=username).exists() or Profile.objects.filter(mobile=username).exists():
            rsp_data = copy.copy(settings.ERROR["EXIST_ERR"])
            rsp_data["msg"] = u"用户已存在"
            return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
        user = User.objects.create_user(username, None, password)
    else:
        rsp_data = copy.copy(settings.ERROR["PARA_ERR"])
        rsp_data["msg"] = u"用户名格式错误"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
        
    user.first_name = firstname
    user.save()
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def update(request):
    """
        func:
                                修改用户信息
        parameters:
            sex:性别
            email:邮箱
            mobile:手机号码
            user_id:用户id
            first_name:昵称
            is_active:用户状态
            user_type:用户类型
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    sex = request.POST["sex"]
    email = request.POST["email"]
    mobile = request.POST["mobile"]
    user_id = request.POST["user_id"]
    first_name = request.POST["first_name"]
    is_active = request.POST["is_active"]
    user_type = request.POST["user_type"]
    if request.user.id == int(user_id):
        rsp_data = copy.copy(settings.ERROR["PERM_ERR"])
        rsp_data["msg"] = u"不能操作当前用户"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    #逻辑操作    
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        rsp_data = copy.copy(settings.ERROR["NOT_EXIST_ERR"])
        rsp_data["msg"] = u"用户不存在"
        return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
    
    if email:
        user.email = email
    user.first_name = first_name
    user.is_active = is_active
    #保存用户
    user.save()
    #用户资料赋值
    profile = {}
    profile["sex"] = sex
    profile["utype"] = user_type
    if mobile:
        profile["mobile"] = mobile
    #更新用户资料
    Profile.objects.filter(user=user).update(**profile)
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def delete(request):
    """
        func:
                                删除用户
        parameters:
            user_ids:用户id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    user_ids = request.POST["user_ids"]
    if user_ids:
        user_ids = user_ids.split(",")
    #逻辑操作    
    User.objects.filter(id__in=user_ids).exclude(id=request.user.id).update(is_active=False)
    #保存用户信息
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')

@login_required
def activate(request):
    """
        func:
                                激活用户
        parameters:
            user_ids:用户id集合
    """
    rsp_data = copy.copy(settings.ERROR["SUCC"])
    #获取并赋值
    user_ids = request.POST["user_ids"]
    if user_ids:
        user_ids = user_ids.split(",")
    #逻辑操作    
    User.objects.filter(id__in=user_ids).exclude(id=request.user.id).update(is_active=True)
    #保存用户信息
    return HttpResponse(json.dumps(rsp_data), mimetype='application/json')
